from fastapi import APIRouter, Query, Depends

from application.utils import get_rich_logger
from authentication.jwt import get_current_user
from domain.authentication import User
from domain.envd import *
from envd.envds import add_new_envd_metadata_record, delete_metadata_record, view_envd_metadata, update_envd_metadata

logger = get_rich_logger()

envd_router = APIRouter(
    prefix="/envd",
    tags=['envd']
)


@envd_router.post("/create")
async def create_new_envd_environment(
        project_name: str,
        build: EnvdBuild,
        current_user: User = Depends(get_current_user)
):
    meta = EnvdInDB(
        project_name=project_name,
        uuid=current_user.uuid.hex,
        build_metadata=build
    )
    logger.debug(f"Build metadata: {meta}")
    new_record = await add_new_envd_metadata_record(
        metadata=meta,
        user=current_user
    )
    return new_record


@envd_router.get("/fetch")
async def get_environment_info(
        envd_id: str | None = Query(
            default=None,
            alias="envd-id",
            title="Target envd record id.",
            description="The Envd environment intended to get information about.",
        ),
        current_user: User = Depends(get_current_user)
):
    metadata_record = await view_envd_metadata(
        record_id=envd_id,
        user=current_user
    )
    return metadata_record


@envd_router.patch("/update")
async def update_envd_environment(
        build: EnvdBuild,
        envd_id: str = Query(
            ...,
            alias="envd-id",
            title="Target envd record id.",
            description="The Envd environment intended to be updated.",
        ),
        current_user: User = Depends(get_current_user)
):
    updated_record = await update_envd_metadata(
        user=current_user,
        update_record_id=envd_id,
        new_envd_build=build
    )
    return updated_record


@envd_router.delete("/delete")
async def delete_environment_from_metastore(
        envd_id: str = Query(
            ...,
            alias="envd-id",
            title="Target envd record id.",
            description="The Envd environment intended to delete.",
        ),
        current_user: User = Depends(get_current_user)
):
    ret = await delete_metadata_record(
        record_id=envd_id,
        user=current_user
    )
    return ret
